package com.rainng.coursesystem.service.teacher;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.rainng.coursesystem.dao.mapper.*;
import com.rainng.coursesystem.manager.teacher.CourseManager;
import com.rainng.coursesystem.model.bo.CourseFormDTO;
import com.rainng.coursesystem.model.entity.*;
import com.rainng.coursesystem.model.vo.response.ResultVO;
import com.rainng.coursesystem.model.vo.response.StudentInfoVO;
import com.rainng.coursesystem.model.vo.response.table.TeacherCourseItemVO;
import com.rainng.coursesystem.service.BaseService;
import com.rainng.coursesystem.util.LessonTimeConverter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("teacher_courseService")
public class CourseService extends BaseService {
    private final CourseManager manager;
    private final LessonTimeConverter lessonTimeConverter;

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private StudentCourseMapper studentCourseMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ClassMapper classMapper;

    @Autowired
    private HomeWorkMapper homeWorkMapper;

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private AnswerMapper answerMapper;


    @Autowired
    private MajorMapper majorMapper;

    public CourseService(CourseManager manager, LessonTimeConverter lessonTimeConverter) {
        this.manager = manager;
        this.lessonTimeConverter = lessonTimeConverter;
    }

    public ResultVO list(Integer keyword, Integer grade) {
        Integer teacherId = getUserId();

        QueryWrapper<CourseEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_teacher_id",teacherId);
        queryWrapper.eq(keyword!=null,"course_id",keyword);
        queryWrapper.eq(grade!=null,"course_grade",grade);

        List<CourseEntity> list = courseMapper.selectList(queryWrapper);

       // List<TeacherCourseItemVO> list = manager.listTeacherCourse(teacherId);
        for (CourseEntity vo : list) {
            vo.setTime(lessonTimeConverter.covertTimePart(vo.getTime()));
        }

        return result(list);
    }

    public ResultVO addCourse(CourseFormDTO dto) {
        Integer userId = getUserId();
        dto.setTeacherId(userId);
        dto.setMaxSize(50);
        manager.addCourse(dto);
        return result("success");
    }

    public ResultVO updateCourse(CourseFormDTO dto) {
        CourseEntity courseEntity = new CourseEntity();
        Integer courseId = dto.getId();
        CourseEntity Orginalcourse = courseMapper.selectById(courseId);
        BeanUtils.copyProperties(Orginalcourse,courseEntity);
        BeanUtils.copyProperties(dto, courseEntity);
        courseEntity.setTime(lessonTimeConverter.revertTimePart(courseEntity.getTime()));
        int success = courseMapper.updateById(courseEntity);
        return result((success == 1));
    }


    @Transactional
    public ResultVO deleteCourse(Integer id) {
        try {
            int success = courseMapper.deleteById(id);

            //课程删除则课程相关作业也删除
            QueryWrapper<HomeworkEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("course_id",id);
            List<HomeworkEntity> homeworkEntityList = homeWorkMapper.selectList(queryWrapper);
            homeWorkMapper.delete(queryWrapper);


            // 同时对应的考试也删除
            QueryWrapper<ExamEntity> examEntityQueryWrapper = new QueryWrapper<>();
            examEntityQueryWrapper.eq("course_id",id);
            examMapper.delete(examEntityQueryWrapper);

            List<Integer> homeworkIds = homeworkEntityList.stream().map(c -> c.getId()).collect(Collectors.toList());
            QueryWrapper<AnswerEntity> answerEntityQueryWrapper = new QueryWrapper<>();
            if (homeworkIds!=null){
                answerEntityQueryWrapper.in("homework_id",homeworkIds);
                answerMapper.delete(answerEntityQueryWrapper);
            }

            return result(success==1);
        }catch (Exception e){
            return failedResult("有学生选修该课程");
        }


    }


    public ResultVO getStudentOfCourse(Integer courseId) {
        QueryWrapper<StudentCourseEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sc_course_id",courseId);
        List<StudentCourseEntity> studentCourseEntityList = studentCourseMapper.selectList(queryWrapper);

        // 如果查询为空则返回
        if(studentCourseEntityList == null || studentCourseEntityList.size() == 0 ) {
            return result("null");
        }

        List<Integer> studentIds = studentCourseEntityList.stream().map(StudentCourseEntity::getStudentId).collect(Collectors.toList());
        List<StudentEntity> studentsInfo = studentMapper.selectList(new QueryWrapper<StudentEntity>().in("student_id", studentIds));

        List<StudentInfoVO> voList = new ArrayList<>();

        // 遍历vo 中给学生对应的班级、专业连表查询
        studentsInfo.forEach(studentEntity -> {
            StudentInfoVO vo = new StudentInfoVO();

            Integer classId = studentEntity.getClassId();
            // 根据课程id查询课程名称
            ClassEntity classInfo = classMapper.selectById(classId);
            vo.setClassName(classInfo.getName());

            String majorName = majorMapper.selectOne(new QueryWrapper<MajorEntity>().eq("major_id", classInfo.getMajorId())).getName();
            vo.setMajorName(majorName);

            BeanUtils.copyProperties(studentEntity,vo);

            voList.add(vo);
        });


        return result(voList);
    }
}
